{% extends "../single_page.html" %}
{% load static %}

{% block specific_page_css %}
	<link rel="stylesheet" href="{% static 'AdminLTE/plugins/select2/css/select2.min.css' %}">
	<link rel="stylesheet" href="{% static 'AdminLTE/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}">
	<style>
		button.button_group1+div+div {
			width: 200px;
			margin-top: 7px;
			margin-left: 1em;
			z-index: 1000;
		}
	  </style>
{% endblock %}

{% block title %}
<title>分析结果管理 测序上机信息</title>
{% endblock %}

{% block header_title %}
<h1>测序上机信息</h1>
{% endblock %}

{% block header_ol %}
	<li class="breadcrumb-item"><a href="/Home/">Home</a></li>
	<li class="breadcrumb-item">SEQ</li>
	<li class="breadcrumb-item active">SequencingInfo</li>
{% endblock %}

{% block page-script %}
<script src="{% static 'AdminLTE/plugins/select2/js/select2.min.js' %}"></script>

<script>
  $(document).ready(function () {
      $("#sidebar_SEQ>a").addClass("active");
	  $("#sidebar_SEQ").addClass("menu-open");
	  $("#sidebar_SEQ>ul>li:eq(0)>a").addClass("active");
	  $(".sidebar").removeAttr("hidden");

	  let model0 = "SequencingInfo";
	  let url0 = '/api/SEQ/' + model0 + '/';
	  let url1 = '/api/LIMS/Methy/MethyCaptureInfo/';
	  let id0 = 0;
      let bulk_update_bool = {% if perms.SEQ.bulk_update_SequencingInfo %} true {% else %} false {% endif %};
      let bulk_delete_bool = {% if perms.SEQ.bulk_delete_SequencingInfo %} true {% else %} false {% endif %};
	  let data1 = {};
	  let poolingLB_id_list = [];
	  $.each($.ajax({
				  url: url1, data: {fields: "id,poolingLB_id"},
				  dataType: 'json', contentType: "application/json",
				  method: "GET", async: false
			  }).responseJSON, function (i, v) {
			data1[v.poolingLB_id]= parseInt(v.id);
			poolingLB_id_list.push(v.poolingLB_id);
	  });

      function update_func(e, id0){
          e.preventDefault();
		    // 递交前检查，一般是检测model的外键是否存在
			let arr = modal2poolingLB_id.val();
			let poolingLB_ids_send = [];
			let unique_dict = {};
			for (let idx in arr) {
				if (unique_dict[arr[idx]] === undefined) {
					unique_dict[arr[idx]] = 1;
				} else {
					unique_dict[arr[idx]] += 1;
					continue;
				}
				if (data1[arr[idx]] === undefined) {
					$('#myModalError').text('错误！！！捕获文库名' + arr[idx] + '不存在，请填写正确的捕获文库名。');
					return
				} else {
					poolingLB_ids_send.push(data1[arr[idx]]);
				}
			}

            let type = $('#type').val();
            let method = '';
            let url_ajax0 = url0;
            let send_data0 = $("#modelForm").find(":not(#poolingLB_id)").serialize() + '&' +
					$.param({ methycaptureinfo: poolingLB_ids_send }, true);
            if (type === 'new') {
                // new
                method = 'POST';
              // POST前检查，一般是检测model的关键字段值是否存在
                data0 = $.ajax({
                    url: url0, dataType: 'json', contentType: "application/json",
                    type: "get", async: false, data: { sequencing_id: $('#sequencing_id').val(), fields: "id" }
                }).responseJSON[0];
                if (data0 !== undefined) {
                    $('#myModalError').text('错误！！！上机文库号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                    return
                }
            } else {
                // edit
                url_ajax0 = url0 + id0 + '/';
                method = 'PUT';
            }

			console.info(">>>>>url_ajax0:", url_ajax0, ";send_data0:",send_data0);
            console.info(">>>>>poolingLB_ids_send:", poolingLB_ids_send);
            $.ajax({
                url: url_ajax0,
                method: method,
                data: send_data0,
                headers: {'X-HTTP-Method-Override': 'PATCH'},
                success: function () {
                    let v_tmp = $('#sequencing_id').val();
                    if (type === 'new') {
                      	databaseRecordAjaxPut('{{ user.id }}', model0, "单项添加", "上机文库号：" + v_tmp);
                      	$('#myModalError').text('添加成功！！！上机文库号：' + v_tmp);
                  	} else {
                      	databaseRecordAjaxPut('{{ user.id }}', model0, "单项更新", "上机文库号：" + v_tmp);
                      	$('#myModalError').text('更新成功！！！上机文库号：' + v_tmp);
                  	}

                    setTimeout(
                      	function () {
                          	window.location.reload(true);
                      	}, 3000
                  	);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#myModalError').text('出现错误！！！请联系管理员');
                    console.info(url_ajax0, method, send_data0);
                    console.info(jqXHR, textStatus, errorThrown)
                }
            });
      }

      let input_params = {
		  "title1_text": "分析结果管理 测序上机信息 总条目数：",
		  "fields": [
              //                    [   0,     1,      2,               3,        4,       5,       6 ]
              // input类型是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, [[value, text]] ]
              // input类型不是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, value ]
              ["sequencing_id", "上机文库号", 1, 0, 1, "text"],
              ["poolingLB_id", "捕获文库名", 1, 1, 1, "select_multiple", []],
              ["send_date", "送测日期", 1, 2, 0, "date", "2000-01-01"],
              ["start_time", "上机时间", 1, 3, 0, "date", "2000-01-01"],
              ["end_time", "下机时间", 1, 4, 0, "date", "2000-01-01"],
              ["machine_id", "机器号", 1, 5, 0, "text", "无"],
              ["chip_id", "芯片号", 1, 6, 0, "text", "无"],
              ["memo", "备注", 1, 7, 0, "text", "无"],
              ["last_modify_time", "上次修改时间", 0],
              ["create_time", "创建时间", 0]
          ],
          "update_func": update_func,
          "delete_func": simple_delete_func,
          "bulkDelete_func": simple_bulkDelete_func,
          "download_excel": '/ADVANCE/download_excel/SEQ_' + model0 + '/'
      };
      single_page_generator(model0, url0, id0, bulk_update_bool, bulk_delete_bool, input_params);

      let modal2poolingLB_id = $('#poolingLB_id').select2({
		  tags: true,
		  maximumSelectionLength: 50,
		  allowClear: true,
		  placeholder: "捕获文库名，必填",
		  multiple: true,
		  maximumInputLength: 25,//允许长度
		  //data: initdata
		  data: poolingLB_id_list
	  });
  });
</script>
{% endblock %}
